

import 'package:flutter/material.dart';
import 'package:flutter_rider/main/widgets/dialog/alert_dialog.dart';
import 'package:flutter_rider/main/widgets/ext/u_text.dart';
import 'package:flutter_rider/main/widgets/state/state_layout.dart';
import 'package:flutter_rider/main/widgets/ui_constant.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import 'package:flutter_svg/svg.dart';
import 'package:flutter_rider/api/api.dart';
import 'package:flutter_rider/event/change_stations_event.dart';
import 'package:flutter_rider/generated/r.dart';
import 'package:flutter_rider/main.dart';
import 'package:flutter_rider/utils/extension.dart';
import 'package:flutter_rider/utils/log.dart';
import 'package:flutter_rider/utils/tip.dart';

import 'package:amap_flutter_base/amap_flutter_base.dart';



class PopStationsList extends StatefulWidget {
  String lat;
  String lng;
  String car_no;
  String  mode;
  int status;
  int car_id;
  int lx;
  PopStationsList(this.lat,  this.lng,  this.car_no,  this.mode,  this.status,  this.car_id,  this.lx);

  @override
  State createState() => _PopCarListState();
}

class _PopCarListState extends State<PopStationsList> {
  final _inputController = TextEditingController(text: "");
  dynamic _data;
  final List _result = [];

  @override
  Widget build(BuildContext context) {
    String stText = " ";
    if (widget.status != null) {
      if (widget.status == 3) {
        stText = " 任务中";
      } else if (widget.status == 2 || widget.status == 5) {
        stText = " 空闲中";
      } else if (widget.status == 4) {
        stText = " 调配中";
      }
    }
    return Container(
      padding: EdgeInsets.only(left: MediaQuery.of(context).padding.left, right: MediaQuery.of(context).padding.right),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.vertical(top: Radius.circular(8.rpx)),
      ),
      child: Column(
        children: [
          8.hspace,
          Container(
            width: 36.rpx,
            height: 5.rpx,
            decoration: BoxDecoration(
              color: Colors.black.withOpacity(0.26),
              borderRadius: BorderRadius.circular(2.rpx),
            ),
          ),
          Container(
            height: 48.rpx,
            alignment: Alignment.center,
            child: UText.get(widget.car_no+stText, Colors.black, 20.rpx, fw: FontWeight.bold),
          ),
          ..._renderCarInfo(),
          16.hspace,
          Container(
            margin: EdgeInsets.only(left: 10.rpx, right: 10.rpx),
            height: 0.5.rpx,
            color: const Color(0xffE7E7E7),
          ),
          16.hspace,
          _renderInput(),
          16.hspace,
          Container(
            margin: EdgeInsets.only(left: 10.rpx, right: 10.rpx),
            height: 0.5.rpx,
            color: const Color(0xffE7E7E7),
          ),
          Expanded(
            child: StateLayout(
              dataCallback: _onDataCallback,
              url: "/home/index",
              childBuilder: _renderContent,
            ),
          ),
        ],
      ),
    );
  }

  _onDataCallback(dynamic data) {
    _data = data;
    List list = [];

    Log.i(_data["station_list"]);
    _data["station_list"].forEach((item) {
      var latlng1 = LatLng(toDouble(widget.lat), toDouble(widget.lng));
      var latlng2 = LatLng(toDouble(item["lat"]), toDouble(item["lng"]));
      var distance = AMapTools.distanceBetween(latlng1, latlng2);
      item["c_distance"] = distance;
      list.add(item);
    });
    list.sort((item1, item2) {
      return (item1["c_distance"]*100 - item2["c_distance"]*100).toInt();
    });

    _result.addAll(list);
  }

  _onTextChange(String text) {
    if (text.isEmpty) {
      setState(() {
        _result.clear();
        _result.addAll(_data["station_list"]);
      });
    } else {
      _result.clear();
      for (int i = 0; i < _data["station_list"].length; i++) {
        var id = _data["station_list"][i]["station_name"] as String;
        id = id.toLowerCase();
        if (id.contains(text)) {
          _result.add(_data["station_list"][i]);
        }
      }
      setState(() {});
    }
  }

  Widget _renderContent(dynamic data) {
    if (_data["station_list"].length == 0) {
      return Center(
        child: UText.getSubText("暂无数据内容"),
      );
    }
    return ListView.separated(
      itemBuilder: _renderItem,
      itemCount: _result.length,
      separatorBuilder: _renderSeparator,
    );
  }

  Widget _renderInput() {
    return Container(
      color: UIColor.color_content,
      padding: EdgeInsets.symmetric(
        horizontal: 16.rpx,
      ),
      child:Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          UText.get("终点", UIColor.color_t1, 16.rpx),
          8.wspace,
          Expanded(
            child: Container(
              child: TextField(
                  onChanged: _onTextChange,
                  controller: _inputController,
                  textInputAction: TextInputAction.done,
                  maxLength: 20,
                  decoration: InputDecoration(
                    constraints: BoxConstraints(minHeight: 44.rpx, maxHeight: 44.rpx),
                    counterText: "",
                    contentPadding: EdgeInsets.symmetric(vertical: 12.rpx, horizontal: 12.rpx),
                    isCollapsed: true,
                    border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(
                          2.rpx,
                        ),
                        borderSide: BorderSide.none),
                    prefixIcon: Padding(
                      padding: EdgeInsets.only(left: 12.rpx, right: 4.rpx),
                      child: Icon(
                        Icons.search,
                        size: 18.rpx,
                        color: Colors.black.withOpacity(0.4),
                      ),
                    ),
                    prefixIconConstraints: BoxConstraints(maxHeight: 16.rpx),
                    hintText: "可输入站点名进行搜索",
                    hintStyle: TextStyle(color: Colors.black.withOpacity(0.4)),
                    filled: true,
                    fillColor: UIColor.color_input,
                    suffixIconConstraints: BoxConstraints(maxHeight: 16.rpx),
                    suffixIcon: _inputController.text.isNotEmpty
                        ? Container(
                      padding: EdgeInsets.only(right: 6.rpx),
                      child: GestureDetector(
                        child: Icon(
                          Icons.close,
                          color: UIColor.color_t3,
                          size: 20.rpx,
                        ),
                        onTap: () {
                          _inputController.text = "";
                          _onTextChange("");
                        },
                      ),
                    )
                    : null,
                  ),
              ),
            ),
          ),
          8.wspace,
        ]
      )
    );
  }

  Widget _renderSeparator(BuildContext context, int index) {
    return Container(
      margin: EdgeInsets.only(left: 10.rpx, right: 10.rpx),
      height: 0.5.rpx,
      color: const Color(0xffE7E7E7),
    );
  }

  Widget _renderItem(BuildContext context, int index) {
    var item = _result[index];
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      child: SizedBox(
        width: double.infinity,
        height: 64.rpx,
        child: Row(
          children: [
            Container(
              margin: EdgeInsets.only(left: 10.rpx, right: 10.rpx),
              padding: EdgeInsets.only(left: 4.rpx, right: 4.rpx),
              width: 32.rpx,
              height: 32.rpx,
              decoration: const BoxDecoration(
                color: Color(0xffE7E7E7),
                borderRadius: BorderRadius.all(Radius.circular(30.0)),
              ),
              child:SvgPicture.asset(R.image_station2, width: 24.rpx, height: 24.rpx),
            ),
            12.wspace,
            Expanded(child: UText.get(item["station_name"], Colors.black, 16.rpx, fw: FontWeight.w600)),
            SizedBox(
                width: 100.rpx,
                child: UText.get(index == 0?'当前临近站点':'', UIColor.color_t4, 16.rpx)),

            24.wspace
          ],
        ),
      ),
      onTap: () {
        Log.i("item",item);
        _inputController.text = item["station_name"];
        CustomAlertDialog.show(context, title:item["station_name"],content: "确定开始调车吗?", onConfirm: () {
          send_dispatch(item["station_id"]);
        });
      },
    );
  }

  List<Widget> _renderCarInfo() {
    return [
      Row(
        children: [
          24.wspace,
          UText.get("当前模式", Colors.black.withOpacity(0.4), 14.rpx),
          8.wspace,
          Expanded(
              child: UText.get(widget.mode, Colors.black, 14.rpx)
          ),
          16.wspace,
        ],
      ),
      12.hspace,
      Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          24.wspace,
          UText.get("车辆位置", Colors.black.withOpacity(0.4), 14.rpx),
          8.wspace,
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              UText.get("Lat: ${widget.lat}", Colors.black, 14.rpx),
              2.hspace,
              UText.get("Lng: ${widget.lng}", Colors.black, 14.rpx),
            ],
          )
        ],
      ),
    ];
  }

  send_dispatch(station_id) {
    var url= "/driver/send_dispatch";
    if(widget.lx == 1) {
      url= "/driver/send_dispatch";
    } else {
      url= "/driver/change_destination";
    }

    var json = {};
    json["car_id"] = (widget.car_id).toString();
    json["station_id"] = (station_id).toString();

    Api.submitx(context, url, data: json, progress: false, success: (data) {
      if(widget.lx == 1) {
        Tip.show(widget.car_no+'调配成功');
      } else {
        Tip.show(widget.car_no+'变更成功');
      }
      eventBus.fire(ChangeStationsEvent());
    }, failTip: "提交失败", fail: (_) {

    });
  }
}